package com.gupao.javavip.netty.push.client.connection;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import lombok.extern.apachecommons.CommonsLog;

@CommonsLog
public abstract class AbstractConnector implements Connector {
    private String host = "localhost";
    private int port = 8080;

    private EventLoopGroup group;
    private Bootstrap client;
    private Channel channel;

    public AbstractConnector(String host, int port) {
        this.host = host;
        this.port = port;

        initClientBootstrap();
    }

    private void initClientBootstrap() {
        group = new NioEventLoopGroup();
        client = new Bootstrap();

        client.group(group)
                .channel(NioSocketChannel.class)
                .handler(buildHandler());
    }

    @Override
    public void connect() {
        try {
            ChannelFuture future = client.connect(host, port);
            this.channel = future.channel();

            afterConnect(future);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        } finally {
            whenShutdown();
        }
    }

    protected void whenShutdown() {
        //优雅关闭 线程组
        group.shutdownGracefully();
    }

    protected void afterConnect(ChannelFuture future) throws Exception {
        future.sync();
        //等待客户端连接端口关闭
        future.channel().closeFuture().sync();
    }

    protected abstract ChannelInitializer<SocketChannel> buildHandler();
}
